$(document).ready(function () {

    $('#btn-reservation').attr('class', 'navbar-btn btn btn-default btn-active');
    $('title').html("预约管理");

    //查看预约
    $('.show-reservation').click(function () {
        var id = $(this).attr('role');
        $(location).attr('href', '/reservation-add?id=' + id + '&update=' + 1);
    });


    // automatically toggle focus between the email modal window and the login form //
    $('#get-user-msg').on('shown.bs.modal', function () {
        $('#msg-tf').focus();
    });

    //删除 已取消和已结束预约的同意和拒绝按钮
    var refuseBtns = $('.refuse-reservation');
    var accpetBtns = $('.accpet-reservation');
    for (var i = 0; i < refuseBtns.length && i < accpetBtns.length; i++) {
        var curRefuseBtn = $(refuseBtns[i]);
        var curAccpetBtn = $(accpetBtns[i]);
        if (curRefuseBtn.attr('status') === 'canceled' || curRefuseBtn.attr('status') === 'finished') {
            curRefuseBtn.hide()
        }
        if (curAccpetBtn.attr('status') === 'canceled' || curAccpetBtn.attr('status') === 'finished') {
            curAccpetBtn.hide()
        }
    }


    retrievePasswordAlert = $('#get-user-msg .alert');
    //给用户发送邮件通知, 预约是否成功
    $('#modify-submit').click(function () {
        var msg = $('#msg-tf').val();
        console.log('--- modify submit ---', msg);
        console.log('--- data ---', data);
        // $('#get-msg-form').submit();
        var pathname = window.location.pathname;
        // $('#get-user-msg').modal('hide');

        $.post('/reservation-update-status', data, function (result) {
            console.log(" account-update-status  ---- return result: ", result);

            if (result.id === 1) {
                //给用户发送通知
                if (msg.trim() !== '') {
                    retrievePasswordAlert.attr('class', 'alert alert-danger');
                    retrievePasswordAlert.html('正在发送...');
                    retrievePasswordAlert.show();

                    $.post('/user-msg', {
                        'user_id': data['user_id'],
                        'msg': msg,
                        'status': data['status']
                    }, function (result2) {
                        console.log("user-msg  ---- return result: ", result2);
                        if (result2.id == 1) {
                            // $('#cancel').html('OK');
                            // $('#modify-submit').hide();

                            retrievePasswordAlert.html('');
                            $('#get-user-msg').modal('hide');
                            generateNotify('', '邮件发送成功', 'success', 3000);
                            setTimeout("$(location).attr('href', window.location.pathname)", 500);
                        } else {
                            retrievePasswordAlert.html('');
                            //发送邮件失败
                            // retrievePasswordAlert.html('邮件发送失败');
                            generateNotify('', '邮件发送失败, 用户邮箱错误', 'danger', 3000);
                        }
                    });

                } else { //不发送邮件
                    $('#get-user-msg').modal('hide');
                    generateNotify('', result.msg, 'success', 3000);
                    setTimeout("$(location).attr('href', window.location.pathname)", 500);
                }
            } else {
                //更新用户状态失败
                $('#get-user-msg').modal('hide');
                generateNotify('', result.msg, 'danger', 3000);
                setTimeout("$(location).attr('href', window.location.pathname)", 500);
            }
        });
    });

    //检查预约是否已经结束
    function isFinished(dataStatus) {
        var status = false;
        if (dataStatus == 'finished') {
            status = true;
            generateNotify('', '该预约已结束', 'danger');
        }
        return status;
    }

    var data;
    //同意预约
    $('.accpet-reservation').click(function () {
        var dataStatus = $(this).attr('status');
        if (isFinished(dataStatus)) { //如果预约已完成
            return;
        }
        if (dataStatus == 'success') {
            generateNotify('', '该预约申请已成功', 'danger');
        } else {
            //设置同意提示信息
            setSuggestions(2);

            var reservationId = $(this).attr('role');
            var userId = $(this).attr('data-target');
            var status = 2; //同意
            data = {'reservation_id': reservationId, 'user_id': userId, 'status': status};

            $('#msg_title').html('同意用户预约申请');
            $('#cancel').html('取消');
            $('#modify-submit').html('确认同意');
            $('#modify-submit').show();
            $('#get-user-msg').modal('show');
        }
    });

    //拒绝预约
    $('.refuse-reservation').click(function () {
        var dataStatus = $(this).attr('status');
        if (isFinished(dataStatus)) { //如果预约已完成
            return;
        }
        if (dataStatus == 'failed') {
            generateNotify('', '该预约申请已被拒绝', 'danger');

        } else {

            //设置拒绝提示信息
            setSuggestions(3);

            var reservationId = $(this).attr('role');
            var userId = $(this).attr('data-target');
            var status = 3; //拒绝
            data = {'reservation_id': reservationId, 'user_id': userId, 'status': status};

            $('#msg_title').html('拒绝用户预约申请');
            // var ev = new EmailValidator();
            $('#cancel').html('取消');
            $('#modify-submit').html('确认拒绝');
            $('#modify-submit').show();
            $('#get-user-msg').modal('show');
        }

    });


    //删除预约,分为管理员、特殊用户 和 普通用户用户两种操作方式
    $('.remove-reservation').click(function () {
        var id = $(this).attr('role');
        var dataStatus = $(this).attr('status'); //当前预约状态
        var data = {'id': id};
        console.log('dataStatus  :   ' + dataStatus);
        var msg;
        var label;
        if (dataStatus == 'finished' || dataStatus == 'failed') { //如果是已完成或者申请失败， 直接删除
            removeReservation(data);
            return;
        } else if (dataStatus === 'success') { //如果已经预约成功，提示用户是否要取消
            msg = '该预约已申请成功，确定要取消该预约吗？';
            label = '确定';
        } else if (dataStatus == 'loading') { //如果是申请中
            msg = '确定删除该预约(申请中)吗?';
            label = '确定';
        } else {//已取消状态
            msg = '是否删除该预约(已取消)记录?';
            label = '确定';
        }

        bootbox.confirm({
            message: msg,
            buttons: {
                confirm: {
                    label: label,
                    className: 'btn-primary'
                },
                cancel: {
                    label: '取消',
                    className: 'btn-default'
                }
            },
            callback: function (result) {
                if (result)
                    removeReservation(data);
            }
        });
    });


    //删除预约 ，在这个页面操作一定要是管理员
    function removeReservation(data) {
        $.post('/account-check', function (result) {
            if (result.id === 1) { //管理员
                $.post('/reservation-delete', data, function (result) {
                    console.log('result id : ' + result.id);
                    if (result.id === 1) { //删除成功
                        var pathname = window.location.pathname;
                        setTimeout(function () {
                            $(location).attr('href', pathname);
                        }, 500);
                        generateNotify('', result.msg, 'success');
                    } else {
                        generateNotify('', result.msg, 'danger');
                    }
                });
            } else {
                generateNotify('', "删除失败，没有删除权限", 'danger');
            }

        });

    }

    $('.star').on('click', function () {
        $(this).toggleClass('star-checked');
    });

    $('.ckbox label').on('click', function () {
        $(this).parents('tr').toggleClass('selected');
    });

    $('.btn-filter').on('click', function () {
        var $target = $(this).data('target');
        if ($target != 'all') {
            $('.table tr').css('display', 'none');
            $('.table tr[data-status="' + $target + '"]').fadeIn('slow');
        } else {
            $('.table tr').css('display', 'none').fadeIn('slow');
        }
    });

    //设置邮件提示
    $("#suggestions").on("click", ".suggestion", function (event) {
        var value = event.currentTarget.textContent;
        // console.log('value ', value);
        $('#msg-tf').val(value);
        // $("#msg-tf").prop('value', value);
    });

    //设置建议提示用户的信息
    function setSuggestions(type) {
        var suggestionUl = $('#suggestions li');
        var suggestions;
        if (type === 2) { //同意
            suggestions = reservationSuccess;
        } else { //拒绝
            suggestions = reservationFailed;
        }

        for (var i = 0; i < suggestionUl.length && i < suggestions.length; i++) {
            // suggestionUl[i].innerHTML = suggestions[i];
            suggestionUl[i].innerHTML = '<a class="label label-info">' + suggestions[i] + '</a>';
        }
    }

});